package cn.myzqu.sign.project.server.utils;

import io.jsonwebtoken.Claims;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * token常用操作工具类
 * @Author: 的川
 * @Date: 2019/1/17.
 */
@Slf4j
public class TokenUtil {

    public static Integer getUserId(HttpServletRequest request) throws Exception{
        String accessToken = request.getHeader("accessToken");
        log.info("accessToken:"+accessToken);
        if(accessToken!=null){
            Claims claims = JWTUtil.validateJWT(accessToken);
            log.info(claims.toString());
            if(claims != null){
                return Integer.parseInt(claims.getId());
            }
        }
        return 0;
    }

    public static String getUserId() throws Exception{
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        String accessToken = request.getHeader("accessToken");
        log.info("accessToken:"+accessToken);
        if(accessToken!=null){
            Claims claims = JWTUtil.validateJWT(accessToken);
            log.info(claims.toString());
            if(claims != null){
                return claims.getId();
            }
        }
        return null;
    }
}
